package 第二周;

/*
 * @author  YxinMiracle
 * @date  2022-04-25 10:42
 * @Gitee: https://gitee.com/yxinmiracle
 */

import java.util.HashMap;
import java.util.Map;

public class LRU {
    int capacity;

    class Node {
        int key;
        int value;
        Node next;
        Node pre;
    }

    Node head = null;
    Node tail = null;
    Map<Integer, Node> h = new HashMap<>();

    public LRU(int capacity) {
        // capacity为lru长度
        this.capacity = capacity;
        head = new Node();
        tail = new Node();
        head.next = tail;
        tail.pre = head;
    }

    public int get(int key) {
        if (!h.containsKey(key)) return -1;
        // 如果有，那么就证明用过了，所有就更新
        Node node = h.get(key);
        remove(node);
        insert(head, node);
        return node.value;
    }

    private void insert(Node head, Node node) {
        node.next = head.next;
        node.next.pre = node;
        head.next = node;
        node.pre = head;
    }

    private void remove(Node node) {
        node.pre.next = node.next;
        node.next.pre = node.pre;
    }

    public void put(int key, int value) {
        if (!h.containsKey(key)) {
            Node node = new Node();
            node.key = key;
            node.value = value;
            h.put(key, node);
            insert(head, node);
            if (h.size() > capacity) {
                h.remove(tail.pre.key);
                remove(tail.pre);
            }
        } else {
            Node node = h.get(key);
            node.value = value;
            remove(node);
            insert(head, node);
        }
    }

    public static void main(String[] args) {
        LRU lRUCache = new LRU(2);
        lRUCache.put(1, 1); // 缓存是 {1=1}
        lRUCache.put(2, 2); // 缓存是 {1=1, 2=2}
        lRUCache.get(1);    // 返回 1
        lRUCache.put(3, 3); // 该操作会使得关键字 2 作废，缓存是 {1=1, 3=3}
        lRUCache.get(2);    // 返回 -1 (未找到)
        lRUCache.put(4, 4); // 该操作会使得关键字 1 作废，缓存是 {4=4, 3=3}
        lRUCache.get(1);    // 返回 -1 (未找到)
        lRUCache.get(3);    // 返回 3
        lRUCache.get(4);    // 返回 4

    }

}
